package com.rankeiot.core.inner.argumet;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.rankeiot.core.data.IScoped;
import com.rankeiot.core.data.ValueGetter;
import com.rankeiot.core.exception.BusinessException;
import com.rankeiot.core.util.StringUtil;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.sagacity.sqltoy.model.QueryExecutor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


@Schema(description = "动态查询")
@Data
public class QueryParams implements IScoped, ValueGetter {
    @Hidden
    @JsonIgnore
    private HashMap<String,Object> params;

    @Hidden
    @JsonIgnore
    private String scope;

    @Schema(description = "排序")
    private String sort;
    @Hidden
    @JsonIgnore
    private String defaultSort="";
    public void setScope(String scope){
        if(params ==null){
            params =new HashMap<>();
        }
        params.put("scope",scope);
    }
    @Override
    public Object get(Object key) {
        return params.get(key);
    }
    public QueryExecutor getQueryExecutor(String sql){
        return new QueryExecutor(sql,(Map<String, Object>) getParams());
    }

    public String getSort(){
        String sort=getStr("sort");
        return StringUtil.isEmpty(sort)?defaultSort:sort;
    }

    public void setDefaultSort(String defaultSort){
        this.defaultSort=defaultSort;
    }
    @Hidden
    @JsonIgnore
    public String getSort(String defaultSort){
        setDefaultSort(defaultSort);
        return getSort();
//        if(sort==null||StringUtil.isEmpty(sort)){
//            return defaultSort;
//        }
//        String[] sortParts=sort.split(",");
//
//        List<String> sortList=new ArrayList<>();
//        for(Map.Entry<String,String> entry: sort.entrySet()){
//            String field=entry.getKey();
//            String type=entry.getValue();
//            if(type==null){
//                continue;
//            }
//            validateSort(field,type);
//            sortList.add(field+" "+type);
//        }
//        if(sortList.size()==0&&StringUtil.isNotEmpty(defaultSort)){
//            return defaultSort;
//        }
//        return StringUtil.join(sortList);
    }

    public Map<String, Object> params() {
        return params;
    }
}
